package com.sj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sj.common.lang.Const;
import com.sj.entity.Article;
import com.sj.entity.Collect;
import com.sj.entity.User;
import com.sj.mapper.CollectMapper;
import com.sj.service.ArticleService;
import com.sj.service.CollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 收藏关注表 服务实现类
 * </p>
 *
 * @author 孙峻
 * @since 2022-03-09
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private ArticleService articleService;

    @Override
    public Boolean checkIsCollect(Integer uid, Integer id, String type) {

        return collectMapper.checkIsCollect(uid, id, type) > 0;
    }

    @Override
    public Long getCollectNum(Integer id, String type) {
        LambdaQueryWrapper<Collect> queryWrapper = Wrappers.<Collect>lambdaQuery().eq(Collect::getType, type);
        if (Const.ARTICLE.equals(type)) {
            queryWrapper.eq(Collect::getArticleId, id);
        }
        if (Const.AUTHOR.equals(type)) {
            queryWrapper.eq(Collect::getAuthorId, id);
        }
        return this.count(queryWrapper);
    }

    @Override
    public Long getFixArticleCollectNum(Integer id, String type) {
        return articleService.lambdaQuery().inSql(true, Article::getId, "select article_id from collect where user_id = " + id + " and type = 'article' and del = 0 ").eq(Article::getType, type).count();
    }

    @Override
    public IPage<Article> getFixArticleTypeList(User user, String articleType, IPage<Article> articlePage) {
        LambdaQueryWrapper<Article> queryWrapper = Wrappers.<Article>lambdaQuery().inSql(true, Article::getId, "select article_id from collect where user_id = " + user.getId() + " and type = 'article' and del = 0 ");
        if (!"".equals(articleType)) {
            queryWrapper.eq(Article::getType, articleType);
        }
        return articleService.page(articlePage, queryWrapper);
    }

    @Override
    public IPage<Article> getCollectArticleList(User user, IPage<Article> articlePage) {
        return this.getFixArticleTypeList(user, "", articlePage);
    }

    @Override
    public Long getUserCollectNum(Integer userId, String type) {
        return collectMapper.getUserCollectNum(userId , type);
    }
}
